package com;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

public class NewFilter implements Filter {

    private String sourceAddress = "localhost";
    private String sourceContext = null;
    private String targetAddress = "127.0.0.1";
    private String targetPort = "80";
    private String targetContext = null;

    @Override
    public void destroy() {
        System.out.println("destroy");

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        System.out.println("doFilter");
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        response.setCharacterEncoding("UTF-8");

        StringBuffer url = request.getRequestURL();
        System.out.println("url:" + url);

        if (url != null && !url.toString().isEmpty()) {
            String urls[] = url.toString().split("//");
            if (urls[1] != null && !"".equals(urls[1])) {
                String ips[] = urls[1].split("/");
                if (ips[0] != null && !"".equals(ips[0])) {
                    String ip = ips[0];
                    String uri = request.getRequestURI();
                    System.out.println("sourceAddress:" + sourceAddress);
                    System.out.println("ip:" + ip);
                    if (sourceAddress.equals(ip)) {
                        System.out.println("重定向");
                        String fullTargetUtl = null;

                        if (targetContext == null || targetContext.trim().isEmpty() || targetContext.trim().equals("null")) {
                            fullTargetUtl = "http://" + targetAddress + ":" + targetPort + uri;
                        } else {
                            String contextPath = request.getContextPath();
                            if (contextPath == null || contextPath.trim().isEmpty() || contextPath.trim().equals("/")) {
                                fullTargetUtl = "http://" + targetAddress + ":" + targetPort + "/" + targetContext + uri;
                            } else {
                                String pureUri = StringUtils.removeStart(uri, contextPath);
                                fullTargetUtl = "http://" + targetAddress + ":" + targetPort + "/" + targetContext + pureUri;
                            }
                        }
                        if (fullTargetUtl.endsWith("/")) {
                            fullTargetUtl = StringUtils.removeEnd(fullTargetUtl, "/");
                        }
                        int port80Index = fullTargetUtl.indexOf(":80/");
                        if (port80Index > 0) {
                            fullTargetUtl = fullTargetUtl.substring(0,port80Index)+"/"+fullTargetUtl.substring(port80Index+4);
                        }
                        if (request.getQueryString()!=null) {
                        	fullTargetUtl = fullTargetUtl + "?" + request.getQueryString();
                        }
                        System.out.println("Full target url :" + fullTargetUtl);
                        response.sendRedirect(fullTargetUtl);
//                        request.setAttribute("url", fullTargetUtl);
//                        request.getRequestDispatcher("index.jsp").forward(request, response);
                    } else {
                    	System.out.println("url不在配置中" + uri);
                        request.getRequestDispatcher(uri).forward(request, response);

                    }
                } else {
                    System.out.println("ips为空");
                }
            }
        } else {
            //跳转到错误页面
            System.out.println("跳转到错误页面");
        }
        System.out.println("结束！！！");

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        sourceAddress = filterConfig.getInitParameter("sourceAddress");
        sourceContext = filterConfig.getInitParameter("sourceContext");
        targetAddress = filterConfig.getInitParameter("targetAddress");
        targetPort = filterConfig.getInitParameter("targetPort");
        targetContext = filterConfig.getInitParameter("targetContext");
    }

}
